package com.ncbee.base.web;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.ncbee.base.config.shiro.annotation.RequiresExtPermissions;
import com.ncbee.base.model.entity.Dept;
import com.ncbee.base.model.vo.TreeVo;
import com.ncbee.base.service.DeptService;
import com.ncbee.base.util.StringUtils;
import com.ncbee.base.web.base.BaseController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author youdianyun
 * @since 2018-11-23
 */
@Controller
@RequestMapping("/dept")
@RequiresExtPermissions("dept:")
public class DeptController extends BaseController<Dept> {
    private static final Logger logger = LoggerFactory.getLogger(DeptController.class);
    @Autowired
    private DeptService deptService;
    @Override
    protected IService<Dept> getTargetService() {
        return deptService;
    }

    @Override
    public String getListPageUrl() {
        return "dept/listPage";
    }

    @Override
    protected String getAddPageUrl() {
        return "dept/addPage";
    }

    @Override
    protected String getEditPageUrl() {
        return "dept/editPage";
    }

    /**
     * 获取组织机构树
     */
    @ResponseBody
    @RequestMapping("showDeptTree")
    public Object showDeptTree(){
        List<TreeVo> list=deptService.getAllDeptTree();
    return list;
    }
    /*
     * 删除当前资源之前，先删除当前资源的子节点
     */
    @Override
    protected void beforeDelete(HttpServletRequest request, String ids) {
        Dept dept=deptService.getById(ids);
        List<Long> idsList=new ArrayList<Long>();
        QueryWrapper<Dept> queryWrapper=new QueryWrapper<Dept>();
        queryWrapper.likeRight("pre_pid",dept.getPrePid()+",");
        //查询当前资源的子资源
        List<Dept> deptList=deptService.list(queryWrapper);
        for(Dept r:deptList){
            idsList.add(r.getId());
        }
        if(idsList.size()>0){
            deptService.removeByIds(idsList);
        }
    }

    /**
     * 新增资源之后,维护子父级之间的关系
     */
    @Override
    protected void afterSave(HttpServletRequest request,Dept dept){
        Long id=dept.getId();//获取返回的主键
        Long pid=dept.getPid();//获取父id
        StringBuffer pidS=new StringBuffer();
        //如果没有选择父节点
        if(pid==null){
            pidS.append(id);
        }else{
            //选择了父节点
            Dept parentDept=deptService.getById(pid);
            String parentPidS=parentDept.getPrePid();//获取父节点的所有上级资源
            pidS.append(parentPidS).append(",").append(id);
        }
        dept.setPrePid(pidS.toString());
        dept.setCreateTime(LocalDateTime.now());
        boolean flag=deptService.updateById(dept);
        logger.info("---------新增资源成功维护子父级关系结果------："+flag);
    }
    /**
     *  显示更新页面之前
     *  查询当前资源以及当前资源子资源
     */
    @Override
    protected void beforeShowEdit(HttpServletRequest request, Dept dept){
        String prePid=dept.getPrePid();
        QueryWrapper<Dept> queryWrapper=new QueryWrapper<Dept>();
        queryWrapper.likeRight("pre_pid",prePid+",");
        //查询子资源
        List<Dept> deptList=deptService.list(queryWrapper);
        if(CollectionUtils.isEmpty(deptList)){
            deptList=new ArrayList<>();
        }
        deptList.add(dept);
        String  deptListStr= JSONObject.toJSONString(deptList);
        request.setAttribute("deptListStr",deptListStr);
    }
    /**
     * 更新记录之前
     */
    @Override
    protected void beforeUpdate(HttpServletRequest request, Dept dept) {
        Long pid=dept.getPid();
        Dept dbDept=deptService.getById(dept.getId());
        Long dbPid=dbDept.getPid();
        //无值相等 未改变
        if(pid==dbPid){
            return;
        }
        //有值相等,未改变
        if(pid!=null&&dbPid!=null){
            if(pid.intValue()==dbPid.intValue()){
                return;
            }
        }
        List<Dept> updateList=new ArrayList<Dept>();
        QueryWrapper<Dept> queryWrapper=new QueryWrapper<Dept>();
        //查询当前资源所有的子资源。
        queryWrapper.likeRight("pre_pid",dept.getPrePid()+",");
        List<Dept> childDeptList=deptService.list(queryWrapper);
        if(pid==null){//当前资源至于顶级节点
            dept.setPrePid(dept.getId()+"");
            for(Dept r:childDeptList){
                String prePid=r.getPrePid();
                String newPrePid= StringUtils.getUpdatePidStr(prePid,dept.getId()+"");
                r.setPrePid(newPrePid);
                updateList.add(r);
            }
        }else{
            Dept parentDept=deptService.getById(pid);
            String parentPrePid=parentDept.getPrePid();//5,6
            String oldPrePid=dept.getPrePid();//7
            String newPrePid= StringUtils.getUpdatePidStr(oldPrePid,dept.getId()+"");
            dept.setPrePid(parentPrePid+","+newPrePid);
            for(Dept r:childDeptList){
                String prePid=r.getPrePid();
                String childNewPrePid= StringUtils.getUpdatePidStr(prePid,dept.getId()+"");
                r.setPrePid(parentPrePid+","+childNewPrePid);
                updateList.add(r);
            }
        }
        if(!CollectionUtils.isEmpty(updateList)){
            boolean flag=deptService.updateBatchById(updateList);
            if(flag){
                logger.info("----成功维护了"+(updateList.size()+1)+"对父子关系---");
            }

        }
        //设置更新时间
        dept.setUpdateTime(LocalDateTime.now());
    }
}

